package com.example.ws.util;

import java.util.concurrent.ConcurrentHashMap;

public class Container {
    public static final Container INSTANCE = new Container();
    
    private static final ConcurrentHashMap<Class<?>, Object> map = new ConcurrentHashMap<>();

    private Container() {}

    public static Container getInstance() {
        return INSTANCE;
    }

    /**
     * 获取指定类型的对象，如果不存在则尝试通过 无参构造 方法创建
     * 
     * @param <T> 继承自 ContainerTag 的类型
     * @param clazz 要获取的类型
     * @return 对应类型的实例
     * @throws RuntimeException 如果无法创建实例
     */
    public synchronized <T> T getObjectByClass(Class<T> clazz) {
        if (clazz == null) {
            throw new IllegalArgumentException("Class argument cannot be null.");
        }
        
        // 尝试从map中获取已存在的实例
        Object obj = map.get(clazz);
        if (obj != null) {
            return clazz.cast(obj);
        }
        
        try {
            
            T instance = clazz.getDeclaredConstructor().newInstance();
            
            // 将新实例存入map
            map.put(clazz, instance);
            
            return instance;
        } catch (Exception e) {
            throw new RuntimeException("Failed to create instance for class: " + clazz.getName(), e);
        }
    }

    /**
     * 存储对象到容器
     * 
     * @param obj 要存储的对象
     * @return Container 实例，支持链式调用
     */
    public synchronized Container putObject(Object obj) {
        if (obj == null) {
            throw new IllegalArgumentException("Object argument cannot be null.");
        }
        
        Class<?> clazz = obj.getClass();
        map.put(clazz, obj);
        return this;
    }
}